//
//  RCShopDetailModifyViewController.m
//  RocketProject
//
//  Created by Wu Chengwei on 13-10-3.
//  Copyright (c) 2013年 Rocket. All rights reserved.
//

#import "RCShopDetailModifyViewController.h"
#import "RCShopManagerDataModel.h"
#import "MBProgressHUD.h"
#import "IManager+ModuleShopManageModify.h"
#import "UIColor-Expanded.h"
#import "CommonDefines.h"
#import "GloableEngineService.h"
#import "AppDelegate.h"
#import "RCFeedbackDataModel.h"
#import "RCChoosePointMapViewController.h"

#define kFormImageFile         @"image_about_textBG.png"
#define kButtonImageFile       @"login_btn.png"

@interface RCShopDetailModifyViewController ()<UITextViewDelegate,MBProgressHUDDelegate,IManagerDelegate,RCChoosePointDelegate>

@property(nonatomic,retain)UIImageView *iconImageView;
@property(nonatomic,retain)UILabel *modifyTypeLabel;
@property(nonatomic,retain)UITextView *modifyTextView;
@property(nonatomic,retain)UIButton *commitButton;
@property(nonatomic,retain)MBProgressHUDEx *progressHub;
@property(nonatomic,assign)int64_t requestID;
@property(nonatomic,retain)RCShopManagerDetailItem *dataModel;
@property(nonatomic,retain)UIButton *locationButton;
@property(nonatomic,assign)CLLocationCoordinate2D coor;

@end

@implementation RCShopDetailModifyViewController

@synthesize iconImageView = _iconImageView;
@synthesize modifyTextView = _modifyTextView;
@synthesize modifyTypeLabel = _modifyTypeLabel;
@synthesize commitButton = _commitButton;
@synthesize progressHub = _progressHub;
@synthesize requestID = _requestID;
@synthesize dataModel = _dataModel;
@synthesize locationButton = _locationButton;
@synthesize coor = _coor;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithDataModel:(RCShopManagerDetailItem *)dataModel{
    self = [super init];
    if (self) {
        self.dataModel = dataModel;
    }
    return self;
}

-(void)dealloc{
    self.iconImageView = nil;
    self.modifyTypeLabel = nil;
    self.modifyTextView = nil;
    self.commitButton = nil;
    self.progressHub.delegate = nil;
    self.progressHub = nil;
    self.dataModel = nil;
    self.locationButton = nil;
    [super dealloc];
}

-(void)loadView{
    [super loadView];
    self.titleLabelText = @"编辑";
    self.navigationItem.titleView = [self createTitleView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    _iconImageView = [[UIImageView alloc]init];
    _iconImageView.backgroundColor = [UIColor clearColor];
    [self.viewContainer addSubview:_iconImageView];
    
    _modifyTypeLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 32, 40, 14)];
    _modifyTypeLabel.backgroundColor = [UIColor clearColor];
    _modifyTypeLabel.textColor = [UIColor colorWithHex:0xff505050];
//    _modifyTypeLabel.textAlignment = UITextAlignmentRight;
    _modifyTypeLabel.font = [UIFont fontWithName:kFontNameHeiti size:14];
    [self.viewContainer addSubview:_modifyTypeLabel];
    
    
    if (_dataModel.type == kShopManagerDetailType_Phone) {
        
        NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"image_shopManager_phone.png"];
        _iconImageView.frame = CGRectMake(14, 32, 13, 13);
        [_iconImageView setImage:[UIImage imageWithContentsOfFile:filePath]];
        _modifyTypeLabel.text = @"电话：";
        
    }else if (_dataModel.type == kShopManagerDetailType_Address){
        
        NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"image_shopManager_address.png"];
        _iconImageView.frame = CGRectMake(14, 30, 10, 14);
        [_iconImageView setImage:[UIImage imageWithContentsOfFile:filePath]];
        _modifyTypeLabel.text = @"地址：";
        
    }else if (_dataModel.type == kShopManagerDetailType_Opentime){
        
        NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"image_shopManager_opentime.png"];
        _iconImageView.frame = CGRectMake(14, 32, 13, 13);
        [_iconImageView setImage:[UIImage imageWithContentsOfFile:filePath]];
        _modifyTypeLabel.text = @"开放时间：";
        
    }else if (_dataModel.type == kShopManagerDetailType_Description){
        
        NSString *filePath = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"image_shopManager_description.png"];
        _iconImageView.frame = CGRectMake(14, 32, 14, 13);
        [_iconImageView setImage:[UIImage imageWithContentsOfFile:filePath]];
        _modifyTypeLabel.text = @"简介：";
        
    }
    
    CGSize size = [_modifyTypeLabel.text sizeWithFont:_modifyTypeLabel.font constrainedToSize:CGSizeMake(200, 20)];
    CGFloat width = size.width;
    _modifyTypeLabel.frame = CGRectMake(30, 32, width, 14);
    width +=30;
    
    UIImageView *formImageView = [[UIImageView alloc]initWithFrame:CGRectMake(width, 19, 306-width, 52)];
    formImageView.backgroundColor = [UIColor clearColor];
    UIImage *formImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kFormImageFile ofType:nil]];
    formImage = [formImage resizableImageWithCapInsets:UIEdgeInsetsMake(3, 3, 3, 3)];
    [formImageView setImage:formImage];
    formImageView.userInteractionEnabled = YES;
    
    _modifyTextView = [[UITextView alloc]initWithFrame:CGRectMake(1, 1, 304-width, 50)];
    _modifyTextView.backgroundColor = [UIColor clearColor];
    _modifyTextView.delegate = self;
    _modifyTextView.returnKeyType = UIReturnKeyDone;
    [formImageView addSubview:_modifyTextView];
    [self.viewContainer addSubview:formImageView];
    [formImageView release];
    
    _locationButton = [[UIButton alloc]initWithFrame:CGRectMake(width, 71, 40, 40)];
    _locationButton.backgroundColor = [UIColor clearColor];
    [_locationButton setImage:[UIImage imageWithContentsOfFile:[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"image_shopManager_address.png"]] forState:UIControlStateNormal];
    
    [_locationButton setImage:[UIImage imageWithContentsOfFile:[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"image_shopManager_address.png"]] forState:UIControlStateHighlighted];
    [_locationButton addTarget:self action:@selector(locationButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    [self.viewContainer addSubview:_locationButton];
    _locationButton.hidden = YES;
    
    
    _commitButton = [[UIButton alloc]initWithFrame:CGRectMake(13, 117, 293, 35)];
    _commitButton.backgroundColor = [UIColor clearColor];
    [_commitButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kButtonImageFile ofType:nil]] forState:UIControlStateNormal];
    [_commitButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kButtonImageFile ofType:nil]] forState:UIControlStateHighlighted];
    _commitButton.titleLabel.font = [UIFont fontWithName:kFontNameLightHeiti size:16];
    [_commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_commitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [_commitButton setTitle:@"提交" forState:UIControlStateNormal];
    [_commitButton setTitle:@"提交" forState:UIControlStateHighlighted];
    [_commitButton addTarget:self action:@selector(commitButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.viewContainer addSubview:_commitButton];
    
    if (_dataModel.type == kShopManagerDetailType_Description) {
        formImageView.frame = CGRectMake(width, 19, 306-width, 152);
        _modifyTextView.frame = CGRectMake(1, 1, 304-width, 150);
        _commitButton.frame = CGRectMake(13, 217, 293, 35);
        
    }
    
    if (_dataModel.type == kShopManagerDetailType_Address) {
        _locationButton.hidden = NO;
    }
}

#pragma UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

-(void)commitButtonClicked{
    NetworkStatus status = [GloableEngineService sharedInstance].netWorkStatus;
    if (status == kNotReachable) {
        [RCAppDelegate alertWithNetworkError];
        return;
    }
    if ([_modifyTextView.text isEqualToString:@""] ) {
        [RCAppDelegate alertWithCustomizeString:@"没有填写任何内容哦！"];
        return;
    }
    
    _commitButton.enabled = NO;
    
    _progressHub = [[MBProgressHUDEx alloc] initWithView:self.view
                                               TopHeight:0
                                        withBottomHeight:0
                                           withLeftWidth:0
                                          withRightWidth:0
                                    withExclusiveObjects:nil];
    _progressHub.delegate = self;
    _progressHub.labelText = @"提交中...";
    [self.view addSubview:_progressHub];
    [self.view bringSubviewToFront:_progressHub];
    [_progressHub show:YES];
    
    if (self.dataModel.type == kShopManagerDetailType_Address) {
        _requestID = [[IManager sharedInstance]requestSubmitShopAddressModifyInfo:self.dataModel.field withContent:_modifyTextView.text withLat:self.coor.latitude withLon:self.coor.longitude withDelegate:self];
    }else{
        _requestID = [[IManager sharedInstance]requestSubmitShopModifyInfo:self.dataModel.field withContent:_modifyTextView.text withDelegate:self];
    }
    
}

-(void)updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        RCFeedbackDataModel *feedbackDataModel = (RCFeedbackDataModel *)dataModel;
        if (feedbackDataModel.errorNO == 0) {
            [RCAppDelegate alertWithCustomizeString:@"提交成功"];
            _commitButton.enabled = NO;
            if (_delegate && [_delegate respondsToSelector:@selector(modifySuccessed:withContent:)]) {
                [_delegate modifySuccessed:self.dataModel.field withContent:_modifyTextView.text];
            }
            
            [self performSelector: @selector(leftButtonClicked) withObject: nil afterDelay: 1.5f];
        }else{
            [RCAppDelegate alertWithCustomizeString:@"提交失败，请稍后重试"];
            _commitButton.enabled = YES;
        }
    }
}

-(void)updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId{
    if (_requestID == requestId) {
        [_progressHub removeFromSuperview];
        [_progressHub release];
        _progressHub = nil;
        [RCAppDelegate alertWithCustomizeString:@"提交失败，请稍后重试"];
        _commitButton.enabled = YES;
    }
}

-(void)locationButtonClicked{
    
    CLLocationCoordinate2D currentLocation = [GloableEngineService sharedInstance].userLocation;
    
    RCChoosePointMapViewController *chooseVC = [[RCChoosePointMapViewController alloc]initWithCoor:currentLocation andName:@"我的位置"];
    chooseVC.delegate = self;
    [self.navigationController pushViewController:chooseVC animated:YES];
    [chooseVC release];
}

-(void)chooseMerchantAddress:(NSString *)address withCoor:(CLLocationCoordinate2D)coor{
    _modifyTextView.text = address;
    self.coor = coor;
}

-(void)leftButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
